//
//  MessageService.m
//  YouthOlympic2014
//
//  Created by Li Yuhang on 14-7-2.
//  Copyright (c) 2014年 mitian. All rights reserved.
//

#import "MessageService.h"
#import "NotificationCenter.h"

@implementation MessageService

-(NSInteger) countUnreadMsg{
    FMDatabase* db = [DBUtil getDatabase];
    FMResultSet* rs = [db executeQuery:@"select count(1) num from messages where is_read = ?" withArgumentsInArray:@[@NO]];
    NSInteger num = 0;
    
    while ([rs next]) {
        num = [rs intForColumn:@"num"];
    }
    [rs close];
    [db close];
    return num;
}

-(NSArray*/*Message*/) getAllMessages{
    FMDatabase* db = [DBUtil getDatabase];
    FMResultSet* rs = [db executeQuery:@"select * from messages order by cid desc"];
    NSMutableArray* messages = [[NSMutableArray alloc]init];
    
    while ([rs next]){
        Message* message = [[Message alloc]init];
        //
        message.cid = [rs longForColumn:@"cid"];
        message.title = [rs stringForColumn:@"title"];
        message.content = [rs stringForColumn:@"content"];
        long datel = [rs longForColumn:@"date"];
        //
        //NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //[dateFormatter setDateFormat:@"yyyy-MM-dd"]; // Change to suit your format
        message.dateStr =  @"TODO";
        message.date = [NSDate dateWithTimeIntervalSince1970:datel];
        
        NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
        [f setNumberStyle:NSNumberFormatterDecimalStyle];
        message.isRead = [f numberFromString:[rs stringForColumn:@"is_read"]];
        //
        [messages addObject:message];
    }
    
    [rs close];
    [db close];
    return [NSArray arrayWithArray:messages];
}

-(Message*) getMessage: (long) msgId{
    FMDatabase* db = [DBUtil getDatabase];
    
    FMResultSet* rs = [db executeQuery:@"select * from message where cid = ? " withArgumentsInArray:@[[NSNumber numberWithLong:msgId]]];
    Message* message = [[Message alloc]init];
    while ([rs next]) {
        message.cid = [rs longForColumn:@"cid"];
        message.title = [rs stringForColumn:@"title"];
        message.content = [rs stringForColumn:@"content"];

        long datel = [rs longForColumn:@"date"];
        //
        //NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        //[dateFormatter setDateFormat:@"yyyy-MM-dd"]; // Change to suit your format
        message.dateStr =  @"TODO";
        message.date = [NSDate dateWithTimeIntervalSince1970:datel];

    }
    
    
    [rs close];
    [db close];
    return message;
}

- (void)pushDeviceToken:(NSData*)token
             completion:(CompletionBlock)completion
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSError* error = nil;
        NSMutableDictionary* result = [[NSMutableDictionary alloc] init];
        
        NSString *TokenStr = [[token description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
        TokenStr = [TokenStr stringByReplacingOccurrencesOfString:@" " withString:@""];
        
        
        NSDictionary* jsonData = [self.api InputIphoneDevNo:TokenStr userId:@""];
        NSString* errorMsg = [[jsonData objectForKey:@"ApiErrorInfo"] objectForKey:@"msg"];
        
        if (errorMsg != nil) {
            error = [NSError errorWithDomain:errorMsg code:400 userInfo:nil];
        }else{
            NSLog(@"pushDeviceToken result is: %@",result);
        }
        
        dispatch_async(dispatch_get_main_queue(), ^{
            completion(result,error);
        });
    });
}

-(void)notificationUnreadMsgCount
{
    //广播当前未读消息数
    NSDictionary* msgInfo = [NSDictionary dictionaryWithObjectsAndKeys:[NSString stringWithFormat:@"%ld",(long)[self countUnreadMsg]],@"count", nil];
    [[NSNotificationCenter defaultCenter] postNotificationName:showMsgInfoNotification
                                                        object:nil
                                                      userInfo:msgInfo];

    NSLog(@"UnreadMsg is :%ld ",(long)[self countUnreadMsg]);
}

-(long) addMessage:(Message*) msg{
    //TODO

    FMDatabase* db = [DBUtil getDatabase];
    NSString *sql = [NSString stringWithFormat:@"insert into messages (title ,content ,is_read ,date) values ('%@','%@',0,%@)",msg.title ,msg.content ,msg.dateStr];
    
    long result =[db executeUpdate:sql];
    NSLog(@"addmsg cid is %ld",result);
    
    [db close];
    
    
    [self notificationUnreadMsgCount];
    return result;
}

-(BOOL) markMessageAsRead:(long) msgId{
    FMDatabase* db = [DBUtil getDatabase];
    BOOL result =[db executeUpdate:@"update messages set is_read = 1 where cid = ?" withArgumentsInArray:@[[NSNumber numberWithLong:msgId]]];
    
    [db close];
    
    [self notificationUnreadMsgCount];
    return result;
}

@end
